package com.yzr.util.converter;

import cn.hutool.core.io.FileUtil;
import com.yzr.util.ConverterUtil;
import com.yzr.util.FileOfType;
import com.yzr.util.FileType;
import lombok.extern.slf4j.Slf4j;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @description office 文件转换pdf工具类
 * @author: yzr
 * @date: 2021/10/29 15:15
 **/
@Slf4j
@Service
public class OfficeConversion implements Conversion {

    @Resource
    private ConverterUtil converterUtil;

    @Override
    public String convert(String filePath, String target) throws IOException {
        // 获取文件名
        if (!FileUtil.isFile(filePath)) throw new FileNotFoundException("文件不存在");

        String type = FileOfType.getTypeByPath(filePath);
        if (!FileType.isOffice(type)) throw new RuntimeException("文件不是office类型");
        return converterUtil.converterPdf(filePath, target, DefaultDocumentFormatRegistry
                .PDF).getAbsolutePath();
    }

    @Override
    public boolean convert(InputStream in, OutputStream out) {
        if (null == in) {
            throw new RuntimeException("读取流不能为空");
        }

        return converterUtil.converterPdf(in, out);
    }

}
